<template>
	<xn-form-container
		:title="formData.id ? '编辑固定资产' : '新增固定资产'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="所属分公司" name="branch">
				<a-select
					v-model:value="formData.branch"
					placeholder="请选择所属分公司"
					:options="branchCityOptions"
					:allowClear="true"
				/>
			</a-form-item>
			<a-form-item label="所属部门" name="deptId">
				<DeptSelectTree
					v-model="formData.deptId"
					placeholder="请选择所属部门"
					ref="deptSelectRef"
					:disabled="!!formData.id"
				/>
			</a-form-item>
			<a-form-item label="资产分类" name="assetCategory">
				<a-select
					v-model:value="formData.assetCategory"
					placeholder="请选择资产分类"
					:options="assetsCategoryOptions"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="资产名称" name="assetName">
				<a-input v-model:value="formData.assetName" placeholder="请输入资产名称" allow-clear />
			</a-form-item>
			<a-form-item label="规格" name="specification">
				<a-input v-model:value="formData.specification" placeholder="请输入规格" allow-clear />
			</a-form-item>
			<a-form-item label="序列号" name="serialNumber">
				<a-input v-model:value="formData.serialNumber" placeholder="请输入序列号" allow-clear />
			</a-form-item>
			<a-form-item label="资产图片" name="multipartFile">
				<!-- 显示上传按钮 -->
				<a-upload
					name="multipartFile"
					:file-list="fileList"
					:before-upload="beforeUpload"
					:on-remove="handleRemove"
					:max-count="1"
					accept="image/*"
					list-type="picture"
					:show-upload-list="true"
				>
					<a-button>
						<upload-outlined />
						上传图片
					</a-button>
				</a-upload>

				<!-- 实时预览上传的图片 -->
				<div v-if="previewImage" class="image-preview" style="margin-top: 10px">
					<a-image :src="previewImage" :width="100" :height="100" />
				</div>

				<!-- 编辑时显示原有图片 -->
				<div v-else-if="formData.id && formData.image && !hasNewImage" class="image-preview" style="margin-top: 10px">
					<a-image :src="jdOssBaseUrl + formData.image" :width="100" :height="100" />
				</div>

				<!-- 编辑模式下显示提示信息 -->
				<div v-if="formData.id && !formData.image && !previewImage && !hasNewImage" class="no-image-tip">暂无图片</div>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import tool from '@/utils/tool'
	import assetsAdminApi from '@/api/hrms/assets/admin/assetsAdminApi'
	import { message } from 'ant-design-vue'
	import { UploadOutlined } from '@ant-design/icons-vue'
	import DeptSelectTree from '@/components/Selector/deptSelectTree.vue'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'
	const branchCityOptions = tool.dictList('BRANCH_CITY')
	const assetsCategoryOptions = tool.dictList('ASSETS_CATEGORY')
	const fileList = ref([])
	const submitLoading = ref(false)
	const previewImage = ref('') // 实时预览图片
	const hasNewImage = ref(false) // 标记是否有新上传的图片

	// 表单数据
	const formData = ref({})

	// 默认要校验的
	const formRules = {
		branch: [required('请选择所属分支')],
		deptId: [required('请选择所属部门')],
		assetCategory: [required('请选择资产分类')],
		assetName: [required('请输入资产名称')]
	}

	// 上传前检查
	const beforeUpload = (file) => {
		const isImage = file.type.startsWith('image/')
		if (!isImage) {
			message.error('只能上传图片文件!')
			return false
		}
		// 生成预览
		const reader = new FileReader()
		reader.onload = (e) => {
			previewImage.value = e.target.result
		}
		reader.readAsDataURL(file)
		fileList.value = [file]
		hasNewImage.value = true
		return false
	}

	// 移除文件
	const handleRemove = () => {
		fileList.value = []
		previewImage.value = ''
		hasNewImage.value = false
		return true
	}

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			formData.value = Object.assign({}, record)
		} else {
			// 新增时清空表单
			formData.value = {}
		}
		// 重置文件相关状态
		fileList.value = []
		previewImage.value = ''
		hasNewImage.value = false
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value?.resetFields()
		fileList.value = []
		formData.value = {}
		previewImage.value = ''
		hasNewImage.value = false
		visible.value = false
		submitLoading.value = false
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const submitData = new FormData()
				// 添加文件（如果存在）
				if (fileList.value.length > 0) {
					submitData.append('multipartFile', fileList.value[0])
				}
				const submitFormData = { ...formData.value }
				delete submitFormData.image
				submitData.append(
					'fixedAssetsAddOrEditBo',
					new Blob([JSON.stringify(submitFormData)], { type: 'application/json' })
				)
				assetsAdminApi
					.insertOrEditWithFile(submitData)
					.then(() => {
						message.success(formData.value.id ? '修改成功' : '新增成功')
						onClose()
						emit('successful')
					})
					.catch((error) => {
						message.error((formData.value.id ? '修改失败: ' : '新增失败: ') + (error.message || ''))
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {
				submitLoading.value = false
			})
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>

<style scoped>
	.image-preview {
		display: flex;
		align-items: center;
	}

	.no-image-tip {
		color: #999;
		font-size: 14px;
	}
</style>
